import React, {Component} from 'react'
import {connect} from 'react-redux';
import Header from "../components/header";
import { Link } from "react-router-dom";

import {List, Button, InputItem,Checkbox, Toast} from 'antd-mobile';
const AgreeItem = Checkbox.AgreeItem;

import {codeUrl} from "../utils/url"
import {userLogin} from "../redux/actions/userAction" 
export class Login extends Component {
  constructor (props){
   super(props)
   this.state= {
    hasError: false,
    username:"",
    password:"",
    code:"",
    remberpw: false,
    codeimg: new Date().getTime()
   }
   this.loginProcess = false;
}
componentWillMount(){
}
componentDidMount() {
  const {username,password} = JSON.parse(localStorage.getItem("userInfo")) || {}
  // if(username && password ){
    this.setState({
      username,
      password
    })
  // }
  this.autoFocusInst.focus();
}
onErrorClick = () => {
  if (this.state.hasError) {
    Toast.info('账号应该是4-12英文字母跟数字组合');
  }
}
onChange = (value) => {
  var temp = value.replace(/\s/g, '')
  if (temp.length > 12 || temp.length < 4 ) {
    this.setState({
      hasError: true,
    });
  } else {
    this.setState({
      hasError: false,
    });
  }
  this.setState({
    username:value,
  });
}
login=()=>{
  const {username,password,code} = this.state;
  if (username == '') {
    Toast.info('请输入用户名');
  } else if ( password == '') {
    Toast.info('请输入密码');
  } else if ( password.length < 6 || password.length > 16) {
    Toast.info('请输入正确的密码');
  }else if (code == '') {
    Toast.info('请输入验证码');
  } else if (code.length !== 4 ) {
    Toast.info('验证码不正确');
    this.setState({
      codeimg: new Date().getTime()
    });
  }else{
    if(this.loginProcess){return }
    const {dispatch} = this.props;
    this.loginProcess = true;
    let _this = this;
    Toast.loading("提交中",0)
   dispatch(userLogin({userName:username,password:password,yzm:code},(ok,msg)=>{
    _this.loginProcess = false;
    Toast.hide()
    if (ok) {
      //alert('登录成功');
      const {username,password} = this.state;
      if(this.state.remberpw){
        localStorage.setItem("userInfo",JSON.stringify({username,password}))
      }else{
        localStorage.setItem("userInfo",JSON.stringify({username}))
        // localStorage.removeItem("userInfo")
      }
      this.props.history.push("/my")
    } else {
      Toast.info(msg);
      _this.setState({
        codeimg: new Date().getTime()
      });
    }
  }))
  }
 
}

handleKeyPress(e) {
  if (e.key == 'Enter') {
      this.login()
  }
  return false;
}
   render() {
   return <div className="login">
        <Header title="登录" {...this.props}></Header>
        <div className="container">
        <List className="login-container">
          <InputItem
            ref={el => this.autoFocusInst = el}
            type="text"
            placeholder="请输入账号"
            error={this.state.hasError}
            onErrorClick={this.onErrorClick}
            onChange={this.onChange}
            value={this.state.username}
          >账号：</InputItem>
            <InputItem
            type="password"
            placeholder="请输入密码"
            onChange={(value)=>{this.setState({password:value})}}
            value={this.state.password}
          >密码：</InputItem>

          <div className="yanzhenma">
            <InputItem
              type="number"
              placeholder=""
              onChange={(value)=>{this.setState({code:value})}}
              onKeyPress={this.handleKeyPress.bind(this)}
              value={this.state.code}
            >验证码：</InputItem>
            <div className="img-code" onClick={()=>{this.setState({codeimg:new Date().getTime()})}}>
                <img src={codeUrl()+"?t=" + this.state.codeimg} alt=""/>
            </div>
          </div>

        </List>
        <div className="remberid clearfix">
          <AgreeItem data-seed="remberId" onChange={e => {this.setState({remberpw: e.target.checked})}}>
              记住密码
          </AgreeItem>
          <Link to="forget">忘记密码？</Link>
          </div>
        <Button type="primary" onClick={this.login}>登录</Button>
        <p>没有账号？立即<Link to="register">注册</Link></p>
        <Button type="ghost" onClick={()=>{this.props.history.push("register")}}>注册</Button>
        </div>
   </div>
   }
}

function mapStateToProps(state) {
  const {user} = state;
  return {
    user
  };
}

export default connect(mapStateToProps)(Login);
